package com.augurit.common.system.service.org.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;

import com.augurit.common.constant.OrgConstant;
import com.augurit.common.dao.AcPartyRoleDao;
import com.augurit.common.dao.AcRoleDao;
import com.augurit.common.dao.AcRoleFuncDao;
import com.augurit.common.dao.AcUserRoleDao;
import com.augurit.common.dao.OmUserPositionDao;
import com.augurit.common.entity.AcRole;
import com.augurit.common.entity.OmPosition;
import com.augurit.common.entity.OmUser;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.system.convert.AcRoleConverter;
import com.augurit.common.system.convert.OmGroupConverter;
import com.augurit.common.system.convert.OmOrgConverter;
import com.augurit.common.system.convert.OmPositionConverter;
import com.augurit.common.system.convert.OmUserConverter;
import com.augurit.common.system.service.org.IAcFunctionService;
import com.augurit.common.system.service.org.IAcModuleService;
import com.augurit.common.system.service.org.IAcRoleService;
import com.augurit.common.system.service.org.IOmGroupService;
import com.augurit.common.system.service.org.IOmOrgService;
import com.augurit.common.system.service.org.IOmPositionService;
import com.augurit.common.system.service.org.IOmUserService;
import com.augurit.common.system.web.org.form.AcApplicationForm;
import com.augurit.common.system.web.org.form.AcFunctionForm;
import com.augurit.common.system.web.org.form.AcRoleForm;
import com.augurit.common.system.web.org.form.OmGroupForm;
import com.augurit.common.system.web.org.form.OmOrgForm;
import com.augurit.common.system.web.org.form.OmPositionForm;
import com.augurit.common.system.web.org.form.OmUserForm;
import com.augurit.common.util.HqlUtils;
import com.augurit.common.util.PageUtils;
import com.augurit.common.util.lang.CollectionUtils;
import com.augurit.common.util.lang.StringUtils;

/**
 * 角色逻辑实现类
 */
@Service
@Transactional
public class AcRoleServiceImpl implements IAcRoleService {

	//查找不具备指定角色的用户列表
	public static final String SELECT_USERS_NOT_WITH_ROLE = "select user from OmUser user, AcUserRole auo where user.userId=auo.userId and auo.roleId!=?";
	
	// DAO 引用
	@Autowired
	private AcRoleDao acRoleDao;

	@Autowired
	private AcPartyRoleDao acPartyRoleDao;

	@Autowired
	private AcRoleFuncDao acRoleFuncDao;

	@Autowired
	private AcUserRoleDao acUserRoleDao;

	@Autowired
	private IAcFunctionService acFunctionService;

	@Autowired
	private IAcModuleService acModuleService;
	
	@Autowired
	private IOmPositionService omPositionService;
	
	@Autowired
	private IOmOrgService omOrgService;
	
	@Autowired
	private IOmUserService omUserService;
	
	@Autowired
	private IOmGroupService omGroupService;
	
	@Autowired
	private ISysCodeService sysCodeService;
	

	/**
	 * 保存角色form对象列表
	 * @param forms 角色form对象列表
	 */
	public void save(List<AcRoleForm> forms) {
		if (forms != null && forms.size() > 0) {
			for (AcRoleForm form : forms)
				acRoleDao.save(form);
		}
	}

	/**
	 * 根据ID获取指定Form对象
	 * @param id 角色id
	 */
	@Transactional(readOnly = true)
	public AcRoleForm get(Long id) {
		return acRoleDao.getForm(id);
	}

	/**
	 * 根据ID集合获取Form对象列表
	 * @param ids 角色ID集合
	 * @return Form对象列表
	 */
	@Transactional(readOnly = true)
	public List<AcRoleForm> get(Long[] ids) {
		if(ids != null && ids.length > 0) {
			String hql = "from AcRole ps where" + HqlUtils.buildOrCondition("ps", "roleId", ids);
			List<AcRole> list = acRoleDao.find(hql);
			return AcRoleConverter.convertToFormList(list);
		}
		return null;
	}
	
	/**
	 * 根据角色编号查找角色列表
	 * @param roleCode 角色编号
	 * @return
	 */
	@Transactional(readOnly = true)
	public AcRoleForm getRolesByCode(String roleCode) {
		AcRole entity = acRoleDao.findUniqueBy("roleCode", roleCode);
		return AcRoleConverter.convertToForm(entity);
	}
	
	@Transactional(readOnly = true)
	public List<AcRoleForm> getRolesByCodeList(List<String> roleCodeList) {
		if(roleCodeList != null && roleCodeList.size() > 0){
			String hql = "from AcRole ps where " + HqlUtils.buildOrCondition("ps", "roleCode", CollectionUtils.toStringArray(roleCodeList));
			List<AcRole> list = acRoleDao.find(hql);
			return AcRoleConverter.convertToFormList(list);
		}else
			return null;
	}
	
	/**
	 * 保存角色Form对象数组
	 * @param forms Form对象数组
	 */
	public void save(AcRoleForm... forms) {
		if (forms != null)
			for (AcRoleForm form : forms)
				acRoleDao.save(form);
	}

	/**
	 * 根据主键ID集合删除多个角色对象
	 * @param ids 业务字典项主键ID集合
	 */
	public void delete(Long... ids) {
		if (ids != null)
			acRoleDao.delete(ids);
	}

	/**
	 * 获取指定机构的关联角色form列表
	 * @param orgId 机构id
	 */
	@Transactional(readOnly = true)
	public List<AcRoleForm> getRolesByOrgId(Long orgId) {
		return getRoles(OrgConstant.PARTY_TYPE_ORG, orgId);
	}

	/**
	 * 获取指定机构的关联角色id列表
	 * @param orgId 机构id
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Long> getRoleIdsByOrgId(Long orgId) {
		return acPartyRoleDao.getRoleIdList(OrgConstant.PARTY_TYPE_ORG, orgId);
	}

	/**
	 * 获取指定的一组机构关联的角色
	 * @param orgIds 机构id数组
	 * @return 角色id列表
	 */
	@Transactional(readOnly = true)
	public List<Long> getRoleIdsByOrgId(List<Long> orgIds) {
		if(orgIds != null) {
			Set<Long> roleIdSet = new HashSet();
			
			for (Long orgId : orgIds) {
				List<Long> roleIds = this.getRoleIdsByOrgId(orgId);
				if (roleIds != null && roleIds.size() > 0)
					roleIdSet.addAll(roleIds);
			}
			
			return CollectionUtils.toLongList(roleIdSet);
		}
		return null;
	}
	
	/**
	 * 获取指定的一组工作组关联的角色
	 * @param groupIds 工作组id数组
	 * @return 角色id列表
	 */
	@Transactional(readOnly = true)
	public List<Long> getRoleIdsByGroupId(List<Long> groupIds) {
		if(groupIds != null) {
			Set<Long> roleIdSet = new HashSet();
			
			for (Long groupId : groupIds) {
				List<Long> roleIds = this.getRoleIdsByGroupId(groupId);
				if (roleIds != null && roleIds.size() > 0)
					roleIdSet.addAll(roleIds);
			}
			
			return CollectionUtils.toLongList(roleIdSet);
		}
		return null;
	}

	/**
	 * 获取指定岗位的关联角色id列表
	 * @param posId 岗位id
	 * @return 角色form对象列表
	 */
	@Transactional(readOnly = true)
	public List<AcRoleForm> getRolesByPosId(Long posId) {
		return acRoleDao.getRolesByPosId(posId);
	}

	/**
	 * 获取指定岗位的关联角色id列表
	 * @param posId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Long> getRoleIdsByPosId(Long posId) {
		return acPartyRoleDao.getRoleIdList(OrgConstant.PARTY_TYPE_POSITION, posId);
	}

	/**
	 * 获取指定的一组岗位关联的角色
	 * @param posIds 岗位id数组
	 * @return 角色id列表
	 */
	@Transactional(readOnly = true)
	public List<Long> getRoleIdsByPosId(List<Long> posIds) {
		if (posIds != null) {
			Set<Long> roleIdSet = new HashSet();

			for (Long posId : posIds) {
				List<Long> roleIds = this.getRoleIdsByPosId(posId);
				if (roleIds != null && roleIds.size() > 0)
					roleIdSet.addAll(roleIds);
			}
			
			return CollectionUtils.toLongList(roleIdSet);
		}
		return null;
	}

	/**
	 * 获取指定工作组的关联角色列表
	 * @param groupId 工作组id
	 * @return 角色form列表
	 */
	@Transactional(readOnly = true)
	public List<AcRoleForm> getRolesByGroupId(Long groupId) {
		return getRoles(OrgConstant.PARTY_TYPE_GROUP, groupId);
	}

	/**
	 * 获取指定工作组所关联的角色分页列表
	 * @param groupId 工作组id
	 * @param page 分页对象
	 * @return 角色form分页对象
	 */
	@Transactional(readOnly = true)
	public Page<AcRoleForm> getRolesByGroupId(Long groupId, Page<AcRoleForm> page){
		if(groupId != null){
			Page<AcRole> pg = PageUtils.newPageInstance(page);
			
			String hql = "select ar from AcRole ar, AcPartyRole apr where apr.roleId=ar.roleId and apr.partyId=?";
			acRoleDao.findPage(pg, hql, groupId);
			List list = AcRoleConverter.convertToFormList(pg.getResult());
			
			PageUtils.copy(pg, list, page);
			return page;
		}
		return null;
	}

	/**
	 * 获取指定工作组的关联角色id列表
	 * @param groupId 工作组id
	 * @return 角色Id列表
	 */
	@Transactional(readOnly = true)
	public List<Long> getRoleIdsByGroupId(Long groupId) {
		return acPartyRoleDao.getRoleIdList(OrgConstant.PARTY_TYPE_GROUP, groupId);
	}

	/**
	 * 获取与组织对象关联的角色form对象集合
	 * @param partyType 组织对象类型
	 * @param partyId  组织对象主键ID
	 * @return 角色form对象列表
	 */
	@Transactional(readOnly = true)
	public List<AcRoleForm> getRoles(String partyType, Long partyId) {
		return acRoleDao.getRoles(partyType, partyId);
	}

	/**
	 * 获取指定用户直接关联的角色列表
	 * @param userId 用户ID
	 * @return 角色form对象列表
	 */
	@Transactional(readOnly = true)
	public List<AcRoleForm> getAllRolesByUserId(Long userId) {
		Long[] roleIds = getAllRoleIdsByUserId(userId);
		List list = acRoleDao.getRoles(roleIds);
		return AcRoleConverter.convertToFormList(list);
	}
	
	/**
	 * 获取指定用户直接或间接关联的角色列表
	 * @param userId 用户ID
	 * @return 角色id集合
	 */
	@Transactional(readOnly = true)
	public Long[] getAllRoleIdsByUserId(Long userId) {
		if (userId == null)
			return null;

		// 获取用户的直接角色
		List<Long> directRoleIds = getDirectRoleIdsByUserId(userId);

		// 获取用户的继承角色
		Long[] extendRoleIds = this.getExtendRoleIdsByUserId(userId);
		if (extendRoleIds != null && extendRoleIds.length > 0) {
			for (Long roleId : extendRoleIds) {
				directRoleIds.add(roleId);
			}
		}

		Set<Long> roleIdSet = CollectionUtils.convertLongListToSet(directRoleIds);
		return CollectionUtils.toLongArray(roleIdSet);
	}

	/**
	 * 获取指定用户继承的角色ID集合
	 * @param userId 用户ID
	 * @return 角色ID集合
	 */
	@Transactional(readOnly = true)
	public Long[] getExtendRoleIdsByUserId(Long userId) {
		//用户继承的角色：包括从机构、工作组和岗位继承的角色
		Set<Long> roleIds = new HashSet();
		
		//（1）用户从他所属机构继承的角色列表
		List<Long> orgRoleIds = null;
		
		//获取用户的上级机构，包括直接的父机构和间接父机构
		List<Long> paretnOrgIds = omOrgService.getAllParentOrgOfUser(userId) ;
		
		if(paretnOrgIds != null && paretnOrgIds.size() > 0){
			//获取用户的上级机构关联的角色，即为用户从他所属机构继承的角色
			orgRoleIds = this.getRoleIdsByOrgId(paretnOrgIds);
		}
			
		if(orgRoleIds != null && orgRoleIds.size() > 0)
			roleIds.addAll(orgRoleIds);
		
		//（2）用户从他所属工作组获得的角色
		List<Long> groupRoleIds = null;
		//获取用户的上级工作组，包括直接的父工作组和间接父工作组
		List<Long> groupIds = omGroupService.getAllParentGroupOfUser(userId);
		if(groupIds != null && groupIds.size() > 0){
			//获取用户的上级工作组关联的角色，即为用户从他所属工作组继承的角色
			groupRoleIds = this.getRoleIdsByGroupId(groupIds);
		}
		
		if(groupRoleIds != null && groupRoleIds.size() > 0)
			roleIds.addAll(groupRoleIds);
		

		// （3）获取用户从他的岗位获得的角色
		List<Long> posIds = omPositionService.getPositionIds(userId);
		List<Long> posRoleIds = this.getRoleIdsByPosId(posIds);
		if(posRoleIds != null && posRoleIds.size() > 0)
			roleIds.addAll(posRoleIds);

		return CollectionUtils.toLongArray(roleIds);
	}
	
	/**
	 * 获取指定用户继承的角色ID集合
	 * @param userId 用户ID
	 * @return 角色Form对象列表
	 */
	@Transactional(readOnly = true)
	public List<AcRoleForm> getExtendedRolesByUserId(Long userId) {
		Long[] roleIds = getExtendRoleIdsByUserId(userId);
		return get(roleIds);
	}
	
	/**
	 * 获取指定角色的角色分页列表
	 * @param page page对象
	 * @param roleIds 角色id数组
	 * @return 包含角色form对象的分页对象
	 */
	@Transactional(readOnly = true)
	public Page<AcRoleForm> getRoles(Page<AcRoleForm> page, Long[] roleIds){
		if( roleIds != null && roleIds.length > 0){
			// 建立新的分页对象
			Page pg = PageUtils.newPageInstance(page);
		
			String hql = "from AcRole ps where " + HqlUtils.buildOrCondition("ps", "roleId", roleIds);
			
			pg = acRoleDao.findPage(pg, hql);
			
			// 转换为Form对象列表并赋值到原分页对象中
			List<AcRoleForm> list = AcRoleConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
			return page;
		}
		return null;
	}

	/**
	 * 分页查询指定用户id获取未授权的角色
	 * 注意：前提是当前用户所拥有的角色范围内进行授权
	 * @param page 分页对象
	 * @param authUserId 授权用户ID
	 * @param authedUserId 被授权用户ID
	 * @return 角色form对象
	 */
	@Transactional(readOnly = true)
	public Page<AcRoleForm> getRolesNotAssociateUser(Page<AcRoleForm> page, Long authUserId, Long authedUserId) {
		Page pg = PageUtils.newPageInstance(page);

		String hql = "select ps from AcRole ps where 1=1" ;

		//查找授权用户所拥有的所有角色ID集合
		if(!this.omUserService.isSystemAdmin(authUserId)){
			Long[] canAuthRoleIds = getAllRoleIdsByUserId(authUserId);
			if(canAuthRoleIds != null && canAuthRoleIds.length > 0) {
				hql = hql + " and (" + HqlUtils.buildOrCondition("ps", "roleId", canAuthRoleIds) + ")";
			}else{
				hql += " and 1!=1";
			}
		}
		
		//查找被授权用户已有的所有角色ID集合
		Long[] authedRoleIds = getAllRoleIdsByUserId(authedUserId);
		if(authedRoleIds != null && authedRoleIds.length > 0) {
			hql = hql + " and " + HqlUtils.buildAndCondition("ps", "roleId", authedRoleIds);
		}

		acRoleDao.findPage(pg, hql);

		// 转换为Form对象列表并赋值到原分页对象中
		List<AcRoleForm> list = AcRoleConverter.convertToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}

	/**
	 * 获取用户的直接角色列表
	 * @param userId 用户ID
	 * @return 角色form对象
	 */
	@Transactional(readOnly = true)
	public List<AcRoleForm> getDirectRolesByUserId(Long userId) {
		List<Long> roleIds = acUserRoleDao.getDirectRoleIdsByUserId(userId);
		List<AcRole> list = acRoleDao.getRoles(CollectionUtils.toLongArray(roleIds));
		return AcRoleConverter.convertToFormList(list);
	}

	/**
	 * 获取用户的直接角色列表
	 * @param userId 用户ID
	 */
	@Transactional(readOnly = true)
	public List<Long> getDirectRoleIdsByUserId(Long userId) {
		return acUserRoleDao.getDirectRoleIdsByUserId(userId);
	}

	/**
	 * 获取指定角色具有的功能列表
	 * @param roleId 角色id
	 * @return 功能form对象列表
	 */
	@Transactional(readOnly = true)
	public List<AcFunctionForm> getFuncsByRoleId(Long roleId, Map<Long, AcApplicationForm> appMapBuffer) {
		if (roleId != null) {
			Long[] funcIds = getFuncIdsByRoleId(roleId);
			return acFunctionService.getFuncs(funcIds, appMapBuffer);
		} else
			return null;
	}

	/**
	 * 获取指定角色ID获取功能ID集合
	 * @param roleId 角色ID
	 * @return 功能ID集合
	 */
	@Transactional(readOnly = true)
	public Long[] getFuncIdsByRoleId(Long roleId){
		if (roleId != null) {
			return CollectionUtils.toLongArray(acRoleFuncDao.getFuncIdsByRoleId(roleId));
		}
		return null;
	}

	/**
	 * 获取指定用户的功能id集合
	 * @param userId 用户id
	 * @return 功能id数组
	 */
	@Transactional(readOnly = true)
	public Long[] getFuncIdsByUserId(Long userId) {
		Set<Long> funcIdsSet = new HashSet<Long>();
		if (userId != null) {
			Long[] roleIds = getAllRoleIdsByUserId(userId);
			if (roleIds != null && roleIds.length > 0) {
				Long[] funIdsByRoles = getFuncIdsByRoles(userId, roleIds);
				if(funIdsByRoles != null && funIdsByRoles.length > 0)
				CollectionUtils.addAll(funcIdsSet, funIdsByRoles);
			}
			
			// 添加用户特别开通的功能集
			Long[] sepcialOpenFuncIds = acFunctionService.getPermittedFuncIdsByUserId(userId);
			if (sepcialOpenFuncIds != null && sepcialOpenFuncIds.length > 0) {
				CollectionUtils.addAll(funcIdsSet, sepcialOpenFuncIds);
			}
			
			// 排除用户特别禁止的功能集
			Long[] specialForbiddenFuncIds = acFunctionService.getForbidenFuncIdsByUserId(userId);
			if (specialForbiddenFuncIds != null && specialForbiddenFuncIds.length > 0) {
				Set<Long> tmpSet = new HashSet();
				CollectionUtils.addAll(tmpSet, specialForbiddenFuncIds);
				
				if(tmpSet != null)
					funcIdsSet.removeAll(tmpSet);
			}
			
			return CollectionUtils.toLongArray(funcIdsSet);
		}

		return null;
	}

	/**
	 * 获取指定用户及角色id集所对应的功能id
	 * @param userId 用户id
	 * @param roleIds 角色id数组
	 * @return 功能id数组
	 */
	@Transactional(readOnly = true)
	public Long[] getFuncIdsByUserIdAndRoleIds(Long userId, Long[] roleIds) {
		Long[] funcIds = null;
		if (userId != null && roleIds != null && roleIds.length > 0) {
			return getFuncIdsByRoles(userId, roleIds);
		}
		return funcIds;
	}

	/**
	 * 获取功能id集
	 * @param userId 用户id
	 * @param roleIds 角色id数组
	 * @return 功能id数组
	 */
	@Transactional(readOnly = true)
	private Long[] getFuncIdsByRoles(Long userId, Long[] roleIds) {
		if (userId != null && roleIds != null && roleIds.length > 0) {
			Set<Long> funcIdsSet = new HashSet<Long>();
			for (Long roleId : roleIds) {
				Long[] funcIds = getFuncIdsByRoleId(roleId);
				if (funcIds != null && funcIds.length > 0)
					CollectionUtils.addAll(funcIdsSet, funcIds);
			}
			if(funcIdsSet.size() > 0)
				return CollectionUtils.toLongArray(funcIdsSet);
		}
		return null;
	}

	/**
	 * 获取拥有指定功能的所有用户
	 * @param funcId 功能id
	 * @return 用户ids 用户id数组
	 */
	@Transactional(readOnly = true)
	public Long[] getUserIdsByFuncId(Long funcId) {
		Set<Long> userIdSet = null;
		if (funcId != null) {
			// 添加从角色中获得指定功能的用户
			userIdSet = new HashSet<Long>();
			Long[] roleIds = this.getRoleIdsByFuncId(funcId);
			if (roleIds != null && roleIds.length > 0) {
				for (Long roleId : roleIds) {
					Long[] userIds = this.getUserIdsByRoleId(roleId);
					
					Long[] orgIds = this.getOrgIdsByRoleId(roleId);
					Long[] userIdsFromOrgs = omOrgService.getAllUserIdsByOrgIds(orgIds);
					
					Long[] groupIds = this.getGroupIdsByRoleId(roleId);
					Long[] userIdsFromGroups = omGroupService.getAllUserIdsByGroupIds(groupIds);
					
					Long[] posIds = this.getPosIdsByRoleId(roleId);
					Long[] userIdsFromPoses = omPositionService.getUserIdsByPosIds(posIds);
					
					if (userIds != null && userIds.length > 0)
						CollectionUtils.addAll(userIdSet, userIds);
					
					if( userIdsFromOrgs != null && userIdsFromOrgs.length > 0)
						CollectionUtils.addAll(userIdSet, userIdsFromOrgs);
					
					if( userIdsFromGroups != null && userIdsFromGroups.length > 0)
						CollectionUtils.addAll(userIdSet, userIdsFromGroups);
					
					if( userIdsFromPoses != null && userIdsFromPoses.length > 0)
						CollectionUtils.addAll(userIdSet, userIdsFromPoses);
				}
			}

			// 添加获得某项特别开通功能的用户
			Long[] userIdsBySpecialOpenedFunc = acFunctionService.getUserIdsByOpenedFuncId(funcId);
			if (userIdsBySpecialOpenedFunc != null
					&& userIdsBySpecialOpenedFunc.length > 0)
				CollectionUtils.addAll(userIdSet, userIdsBySpecialOpenedFunc);

			// 排除被禁止某项特别功能的用户
			Long[] userIdsBySpcialForbidenFunc = acFunctionService
					.getUserIdsByForbidenFuncId(funcId);
			if (userIdsBySpcialForbidenFunc != null
					&& userIdsBySpcialForbidenFunc.length > 0) {
				Set<Long> tmpSet = new HashSet();
				CollectionUtils.addAll(tmpSet, userIdsBySpcialForbidenFunc);
				userIdSet.removeAll(tmpSet);
			}
			return CollectionUtils.toLongArray(userIdSet);
		}

		return null;
	}

	/**
	 * 获取拥有指定功能的角色id集合
	 * @param funcId 功能id
	 * @return 角色id数组
	 */
	@Transactional(readOnly = true)
	public Long[] getRoleIdsByFuncId(Long funcId) {
		if (funcId != null)
			return acRoleFuncDao.getRoleIdsByFuncId(funcId);
		return null;
	}

	/**
	 * 获取指定角色ID集合的功能ID集合
	 * @param roleIds 角色ID集合
	 * @return 功能ID集合
	 */
	@Transactional(readOnly = true)
	public Long[] getFuncIdsByRoleIds(Long[] roleIds) {
		Set<Long> funcIdsSet = new HashSet<Long>();

		if (roleIds != null && roleIds.length > 0) {
			for (Long roleId : roleIds) {
				Long[] funcIds = getFuncIdsByRoleId(roleId);
				CollectionUtils.addAll(funcIdsSet, funcIds);
			}
		}

		return CollectionUtils.toLongArray(funcIdsSet);
	}

	/**
	 * 添加角色
	 * @param form 角色form对象
	 */
	public void addRoleCascade(AcRoleForm form) {
		acRoleDao.save(form);
	}

	/**
	 * 删除角色
	 * 注意：不能删除系统管理员角色
	 * @param roleId 角色id
	 */
	public void deleteRoleCascade(Long roleId) {
		
		AcRole entity = this.acRoleDao.get(roleId);
		
		if(entity != null && entity.getRoleCode() != null 
				&& !entity.getRoleCode().equals(OrgConstant.ROLE_ADMIN_CODE)){
		
			// 1：删除角色关联的功能,操作关联表AC_ROLE_FUNC
			acRoleFuncDao.deleteByRoleId(roleId);
	
			// 2:删除角色关联的用户,操作关联表AC_USER_ROLE
			acUserRoleDao.deleteByRoleId(roleId);
	
			// 3:删除角色关联的机构、岗位、工作组，操作关联表AC_PARTY_ROLE
			acPartyRoleDao.deleteByRoleId(roleId);
	
			// 4:删除角色,操作表AC_ROLE
			acRoleDao.delete(entity);
		}
	}
	
	/**
	 * 删除角色列表
	 * @param roleIds 角色id数组
	 */
	public void deleteRoleCascade(Long[] roleIds) {
		if (roleIds != null && roleIds.length > 0) {
			for (int i = 0; i < roleIds.length; i++)
				deleteRoleCascade(roleIds[i]);
		}

	}

	/**
	 * 向指定角色中添加指定功能
	 * @param roleId 角色id;
	 * @param funcId 功能id;
	 */
	public void associateFuncToRole(Long roleId, Long funcId) {
		if (roleId != null && funcId != null) {

			// 获取指定功能的模块id
			Long moduleId = acFunctionService.getModuleId(funcId);

			if (moduleId != null) {
				// 获取指定功能所在的应用id
				Long appId = acModuleService.getAppId(moduleId);
				// 添加关联
				if (appId != null) {
					acRoleFuncDao
							.addAcRoleFunc(roleId, funcId, moduleId, appId);
				}
			}
		}
	}

	/**
	 * 向指定角色中添加指定功能列表
	 * @param roleId 角色id
	 * @param funcIds 功能id列表
	 */
	public void associateFuncToRole(Long roleId, Long[] funcIds) {
		if (roleId != null && funcIds != null && funcIds.length > 0) {
			for (Long funcId : funcIds) {
				associateFuncToRole(roleId, funcId);
			}
		}
	}

	/**
	 * 向指定角色中添加指定模块
	 * @param roleId 角色id
	 * @param moduleId 模块id
	 */
	public void associateModuleToRole(Long roleId, Long moduleId) {
		if (roleId != null && moduleId != null) {
			// 获取模块所在的应用的id
			Long appId = acModuleService.getAppId(moduleId);
			if (appId != null) {
				// 找出模块下的所有的功能
				List<AcFunctionForm> list = acModuleService
						.getAllFuncs(moduleId);
				if (list != null && list.size() > 0) {
					for (AcFunctionForm form : list) {
						Long funcId = form.getFuncId();
						acRoleFuncDao.addAcRoleFunc(roleId, funcId, moduleId,
								appId);
					}
				}
			}
		}
	}

	/**
	 * 向指定角色中添加指定模块列表
	 * @param roleId 角色id
	 * @param moduleIds 模块ids
	 */
	public void associateModuleToRole(Long roleId, Long[] moduleIds) {
		if (roleId != null && moduleIds != null && moduleIds.length > 0) {
			for (Long moduleId : moduleIds) {
				associateModuleToRole(roleId, moduleId);
			}
		}
	}

	/**
	 * 向指定角色中添加应用
	 * @param roleId 角色id
	 * @param appId 应用id
	 */
	public void associateAppToRole(Long roleId, Long appId) {
		Long[] moduleIds = acModuleService.getModuleIds(appId);
		if (moduleIds != null && moduleIds.length > 0) {
			for (Long moduleId : moduleIds)
				associateModuleToRole(roleId, moduleId);
		}
	}

	/**
	 * 向指定角色中添加应用列表
	 * @param roleId 角色id
	 * @param appIds 应用id
	 */
	public void associateAppToRole(Long roleId, Long[] appIds) {
		if (roleId != null && appIds != null && appIds.length > 0) {
			for (Long appId : appIds) {
				associateAppToRole(roleId, appId);
			}
		}
	}

	/**
	 * 使指定角色不具有某项功能
	 * @param roleId 角色id
	 * @param funcId 功能id
	 */
	public void disAssociateFuncFromRole(Long roleId, Long funcId) {
		if (roleId != null && funcId != null) {
			List<Long> list = acRoleFuncDao.getRfIdsByRoleIdAndFuncId(roleId,
					funcId);
			if (list != null && list.size() > 0) {
				Long[] ids = CollectionUtils.toLongArray(list);
				acRoleFuncDao.delete(ids);
			}
		}
	}

	/**
	 * 使指定角色不具有多项功能
	 * @param roleId 角色id
	 * @param funcIds 功能id数组
	 */
	public void disAssociateFuncFromRole(Long roleId, Long[] funcIds) {
		if (roleId != null && funcIds != null && funcIds.length > 0) {
			for (Long funcId : funcIds) {
				disAssociateFuncFromRole(roleId, funcId);
			}
		}
	}

	/**
	 * 是指定角色不具有某一个模块的功能
	 * @param roleId 角色id
	 * @param moduleId 模块id
	 */
	public void disAssociateModuleFromRole(Long roleId, Long moduleId) {
		// TODO Auto-generated method stub
		List<Long> list = acRoleFuncDao.getRfIdsByRoleIdAndModuleId(roleId,
				moduleId);
		if (list != null && list.size() > 0) {
			Long[] ids = CollectionUtils.toLongArray(list);
			acRoleFuncDao.delete(ids);
		}

	}

	/**
	 * 使指定角色不具有某一应用的功能
	 * @param roleId
	 * @param appId
	 */
	public void disAssociateAppFromRole(Long roleId, Long appId) {
		List<Long> list = acRoleFuncDao.getRfIdsByRoleIdAndAppId(roleId, appId);
		if (list != null && list.size() > 0) {
			Long[] ids = CollectionUtils.toLongArray(list);
			acRoleFuncDao.delete(ids);
		}
	}

	/**
	 * 分页显示所有的角色列表
	 * @param page page对象
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<AcRoleForm> getAllRoles(Page<AcRoleForm> page) {
		// 建立新的分页对象
		Page<AcRole> pg = PageUtils.newPageInstance(page);

		// 按过滤条件分页查找对象
		String hql = "from AcRole ps";
		pg = acRoleDao.findPage(pg, hql);

		// 转换为Form对象列表并赋值到原分页对象中
		List<AcRoleForm> list = AcRoleConverter.convertToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}

	/**
	 * 多条件分页查询所有的角色列表
	 * @param page page对象，包含分页参数
	 * @param form form对象，包含查询条件
	 * @return 分页对象
	 */
	@Transactional(readOnly = true)
	public Page<AcRoleForm> getAllRoles(Page<AcRoleForm> page, AcRoleForm form) {
		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);

		StringBuffer hql = new StringBuffer("from AcRole ps where 1=1");
		List values = new ArrayList();

		if (form != null) {
			if (form.getRoleCode() != null
					&& form.getRoleCode().trim().length() > 0) {
				hql.append(" and ps.roleCode like ?");
				values.add("%" + form.getRoleCode() + "%");
			}
			if (form.getRoleName() != null
					&& form.getRoleName().trim().length() > 0) {
				hql.append(" and ps.roleName like ?");
				values.add("%" + form.getRoleName() + "%");
			}
		}
		
		//排序
		hql.append(HqlUtils.buildOrderBy(page, "ps"));

		acRoleDao.findPage(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<AcRoleForm> list = AcRoleConverter.convertToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}

	/**
	 * 获取所有的角色
	 * @return 角色列表
	 */
	@Transactional(readOnly = true)
	public List<AcRoleForm> getAllRoles() {
		return acRoleDao.getAllRoles();
	}

	/**
	 * 获取与指定角色关联的用户id集合
	 * @param roleId 角色id
	 * @return 用户id数组
	 */
	@Transactional(readOnly = true)
	public Long[] getUserIdsByRoleId(Long roleId) {
		if (roleId != null)
			return CollectionUtils.toLongArray(acUserRoleDao.getUserIdsByRole(roleId));
		return null;
	}
	
	
	/**
	 * 根据角色id获取具有该角色的机构id数组
	 * @param roleId 角色id
	 * @return 机构id数组
	 */
	public Long[] getOrgIdsByRoleId(Long roleId){
		if( roleId != null){
			return acPartyRoleDao.getOrgIdsByRole(roleId);
		}
		return null;
	}
	
	/**
	 * 根据角色id获取具有该角色的工作组id数组
	 * @param roleId 角色id
	 * @return 工作组id数组
	 */
	public Long[] getGroupIdsByRoleId(Long roleId){
		if( roleId != null){
			return acPartyRoleDao.getGroupIdsByRole(roleId);
		}
		return null;
	}
	
	
	/**
	 * 根据角色id获取具有该角色的岗位id
	 * @param roleId 角色id
	 * @return 岗位id数组
	 */
	@Transactional(readOnly = true)
	public Long[] getPosIdsByRoleId(Long roleId){
		if( roleId != null){
			return acPartyRoleDao.getPositionsIdsByRoleId(roleId);
		}
		return null;
	}

	/**
	 * 分页查询与指定角色关联的所有用户
	 * @param page 分页参数
	 * @param roleId 角色id
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmUserForm> getUsersByDirectRoleId(Page<OmUserForm> page, Long roleId) {

		if (roleId != null) {
			Page pg = PageUtils.newPageInstance(page);
			
			String hql = "select os from AcUserRole ps, OmUser os where ps.userId=os.userId and ps.roleId=?";
			
			//排序
			hql += HqlUtils.buildOrderBy(page, "os");
			
			pg = acUserRoleDao.findPage(pg, hql, roleId);
			
			List<OmUserForm> list = OmUserConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
			return page;
		}
		return null;
	}

	/**
	 * 分页查询不与指定角色关联的用户列表
	 * @param page 分页对象
	 * @param roleId 角色id
	 * @param userForm 用户form对象，包含查询条件
	 * @return 包含用户form的分页对象
	 */
	@Transactional(readOnly = true)
	public Page<OmUserForm> getUsersNotAssociateRole(Page<OmUserForm> page, Long roleId, OmUserForm userForm) {
		if(roleId != null){
			Page pg = PageUtils.newPageInstance(page);

			Long[] userIds = CollectionUtils.toLongArray(acUserRoleDao.getUserIdsByRole(roleId));
			StringBuffer hql = new StringBuffer("select ps from OmUser ps where 1 = 1");
			if (userIds != null && userIds.length > 0) {
				String condition = HqlUtils.buildAndCondition("ps", "userId",userIds);
				hql.append(" and ");
				hql.append(condition);
			}

			List values = new ArrayList();

			if (userForm != null) {
				if (StringUtils.isNotBlank(userForm.getUserCode())) {
					hql.append(" and ps.userCode like ?");
					values.add("%" + userForm.getUserCode() + "%");
				}
				if (StringUtils.isNotBlank(userForm.getUserName())) {
					hql.append(" and ps.userName like ?");
					values.add("%" + userForm.getUserName() + "%");
				}
			}
			
			hql.append(HqlUtils.buildOrderBy(page, "ps"));
			acUserRoleDao.findPage(pg, hql.toString(), values);

			List<OmUserForm> list = OmUserConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
			return page;
		}
		return null;
	}

	/**
	 * 查询与指定角色关联的所有用户
	 * @param roleId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<OmUserForm> getUsersByDirectRoleId(Long roleId) {
		if (roleId != null) {
			String hql = "select os from AcUserRole ps, OmUser os where ps.userId=os.userId and ps.roleId=?";
			List<OmUser> list = acUserRoleDao.find(hql, roleId);
			return OmUserConverter.convertToFormList(list);
		}
		return null;
	}

	/**
	 * 查询与指定角色关联的所有用户
	 * @param roleId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<OmUserForm> getUsersByDirectRoleCode(String roleCode) {
		if (roleCode != null && roleCode.trim().length() > 0) {
			String hql = "select os from AcRole ar, AcUserRole ps, OmUser os where ar.roleId=ps.roleId and ps.userId=os.userId and ar.roleCode=?";
			List<OmUser> list = acUserRoleDao.find(hql, roleCode);
			return OmUserConverter.convertToFormList(list);
		}
		return null;
	}
	
	/**
	 * 查询不与指定角色关联的用户列表
	 * @param roleId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<OmUserForm> getUsersNotAssociateRole(Long roleId) {
		if (roleId != null) {
			String hql = SELECT_USERS_NOT_WITH_ROLE;
			List<OmUser> list = acUserRoleDao.find(hql, roleId);
			return OmUserConverter.convertToFormList(list);
		}
		return null;
	}

	/**
	 * 分页查询与指定角色关联的所有机构
	 * @param page
	 * @param roleId
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmOrgForm> getOrgsByRole(Page<OmOrgForm> page, Long roleId, Map<String, List<SysCodeForm>> sysCodeBuffer) {
		if (roleId != null) {
			Page pg = PageUtils.newPageInstance(page);
			
			String hql = "select os from AcPartyRole ps, OmOrg os where ps.partyId=os.orgId and ps.partyType=? and ps.roleId=?";

			//排序
			hql += HqlUtils.buildOrderBy(page, "os");
			
			pg = acPartyRoleDao.findPage(pg, hql, OrgConstant.PARTY_TYPE_ORG, roleId);
			
			// 转换为Form对象列表并赋值到原分页对象中
			List<OmOrgForm> list = OmOrgConverter.convertToFormList(pg.getResult(),
					sysCodeService.getItems(OrgConstant.SYS_CODE_ORG_TYPE, sysCodeBuffer),
					sysCodeService.getItems(OrgConstant.SYS_CODE_ORG_GRADE, sysCodeBuffer),
					sysCodeService.getItems(OrgConstant.SYS_CODE_ORG_STATUS, sysCodeBuffer));
			
			PageUtils.copy(pg, list, page);
			return page;
		}
		return null;
	}
	
	/**
	 * 分页查询与指定角色关联的所有工作组
	 * @param page
	 * @param roleId
	 * @param sysCodeBuffer
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmGroupForm> getGroupsByRole(Page<OmGroupForm> page, Long roleId, Map<String, List<SysCodeForm>> sysCodeBuffer) {
		if (roleId != null) {
			Page pg = PageUtils.newPageInstance(page);
			
			String hql = "select os from AcPartyRole ps, OmGroup os where ps.partyId=os.groupId and ps.partyType=? and ps.roleId=?";

			//排序
			hql += HqlUtils.buildOrderBy(page, "os");
			
			acPartyRoleDao.findPage(pg, hql, OrgConstant.PARTY_TYPE_GROUP, roleId);
			
			// 转换为Form对象列表并赋值到原分页对象中
			List<OmGroupForm> list = OmGroupConverter.convertToFormList(pg.getResult(),
					omOrgService.getAll(),
					omGroupService.getAllGroups(),
					sysCodeService.getItems(OrgConstant.SYS_CODE_GROUP_TYPE, sysCodeBuffer),
					sysCodeService.getItems(OrgConstant.SYS_CODE_GROUP_STATUS, sysCodeBuffer));
			
			PageUtils.copy(pg, list, page);
			return page;
		}
		return null;
	}

	/**
	 * 分页查询不与指定角色关联的所有机构，多条件查询
	 * @param page 分页对象
	 * @param roleId 角色id
	 * @param orgForm 机构form
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmOrgForm> getOrgsNotAssociateRole(Page<OmOrgForm> page, Long roleId, OmOrgForm orgForm, Map<String, List<SysCodeForm>> sysCodeBuffer) {
		if (roleId != null) {
			Page pg = PageUtils.newPageInstance(page);

			Long[] orgIds = acPartyRoleDao.getOrgIdsByRole(roleId);
			StringBuffer hql = new StringBuffer("select ps from OmOrg ps where 1 = 1");
			if (orgIds != null && orgIds.length > 0) {
				String conidition = HqlUtils.buildAndCondition("ps", "orgId", orgIds);
				hql.append(" and ");
				hql.append(conidition);
			}

			List values = new ArrayList();

			if (orgForm != null) {
				if (StringUtils.isNotBlank(orgForm.getOrgCode())) {
					hql.append(" and ps.orgCode like ?");
					values.add("%" + orgForm.getOrgCode() + "%");
				}
				if (StringUtils.isNotBlank(orgForm.getOrgName())) {
					hql.append(" and ps.orgName like ?");
					values.add("%" + orgForm.getOrgName() + "%");
				}
			}
			//排序
			if(page.getOrderBy() != null && page.getOrderBy().trim().length() > 0){
				hql.append(" order by ps.");
				hql.append(page.getOrderBy());
				hql.append(" ");
				hql.append(page.getOrder());
			}

			pg = acPartyRoleDao.findPage(pg, hql.toString(), values);

			// 转换为Form对象列表并赋值到原分页对象中
			List<OmOrgForm> list = OmOrgConverter.convertToFormList(pg.getResult(),
					sysCodeService.getItems(OrgConstant.SYS_CODE_ORG_TYPE, sysCodeBuffer),
					sysCodeService.getItems(OrgConstant.SYS_CODE_ORG_GRADE, sysCodeBuffer),
					sysCodeService.getItems(OrgConstant.SYS_CODE_ORG_STATUS, sysCodeBuffer));
			
			PageUtils.copy(pg, list, page);
			return page;
		}
		return null;
	}
	
	/**
	 * 分页查询不与指定角色关联的所有工作组
	 * @param page 分页参数
	 * @param roleId 角色id
	 * @param groupForm 工作组form对象
	 * @return 包含工作组form对象的分页对象
	 */
	public Page<OmGroupForm> getGroupsNotAssociateRole(Page<OmGroupForm> page, Long roleId, OmGroupForm groupForm, Map<String, List<SysCodeForm>> sysCodeBuffer){
		if (roleId != null) {
			Page pg = PageUtils.newPageInstance(page);

			Long[] groupIds = acPartyRoleDao.getGroupIdsByRole(roleId);
			StringBuffer hql = new StringBuffer("select ps from OmGroup ps where 1 = 1");
			if (groupIds != null && groupIds.length > 0) {
				String conidition = HqlUtils.buildAndCondition("ps", "orgId", groupIds);
				hql.append(" and ");
				hql.append(conidition);
			}

			List values = new ArrayList();

			if (groupForm != null) {
				if (StringUtils.isNotBlank(groupForm.getGroupName())) {
					hql.append(" and ps.groupName like ?");
					values.add("%" + groupForm.getGroupName() + "%");
				}
				
				if(StringUtils.isNotBlank(groupForm.getGroupType())){
					hql.append(" and ps.groupType = ?");
					values.add(groupForm.getGroupType());
				}
			}
			//排序
			if(page.getOrderBy() != null && page.getOrderBy().trim().length() > 0){
				hql.append(" order by ps.");
				hql.append(page.getOrderBy());
				hql.append(" ");
				hql.append(page.getOrder());
			}

			pg = acPartyRoleDao.findPage(pg, hql.toString(), values);

			// 转换为Form对象列表并赋值到原分页对象中
			List<OmGroupForm> list = OmGroupConverter.convertToFormList(pg.getResult(),
					omOrgService.getAll(),
					omGroupService.getAllGroups(),
					sysCodeService.getItems(OrgConstant.SYS_CODE_GROUP_TYPE, sysCodeBuffer),
					sysCodeService.getItems(OrgConstant.SYS_CODE_GROUP_STATUS, sysCodeBuffer));
			
			PageUtils.copy(pg, list, page);
			return page;
		}
		return null;
	}

	/**
	 * 查询与指定角色关联的机构
	 * @param roleId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<OmOrgForm> getOrgsByRole(Long roleId) {
		return acPartyRoleDao.getOrgsByRoleId(roleId);
	}

	/**
	 * 查询不与指定角色关联的机构
	 * @param roleId
	 * @return
	 */
	public List<OmOrgForm> getOrgsNotAssociateRole(Long roleId) {
		return acPartyRoleDao.getOrgsNotAssociateRole(roleId);
	}

	/**
	 * 分页查询与指定角色关联的所有岗位
	 * @param page
	 * @param roleId
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmPositionForm> getPositionsByRole(Page<OmPositionForm> page,
			Long roleId) {
		if (roleId != null) {
			Page pg = PageUtils.newPageInstance(page);
			String hql = "select os from AcPartyRole ps, OmPosition os where ps.partyId=os.posId and ps.partyType=? and ps.roleId=?";

			//排序
			hql += HqlUtils.buildOrderBy(page, "os");
			
			acPartyRoleDao.findPage(pg, hql, OrgConstant.PARTY_TYPE_POSITION, roleId);
			
			List<SysCodeForm> statusList = sysCodeService.getItems(OrgConstant.SYS_CODE_ORG_STATUS);
			List<OmPositionForm> list = OmPositionConverter.convertToFormList(pg.getResult(),statusList);
			PageUtils.copy(pg, list, page);
			return page;
		}
		return null;
	}

	/**
	 * 分页查询不与指定角色关联的所有岗位
	 * @param page
	 * @param roleId
	 * @param form
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmPositionForm> getPositionsNotAssociateRole(Page<OmPositionForm> page, Long roleId, OmPositionForm form) {
		
		if (roleId != null) {
			Page pg = PageUtils.newPageInstance(page);
			
			
			
			StringBuffer hql = new StringBuffer("select ps from OmPosition ps where 1=1");
			
			
			Long[] posIds = acPartyRoleDao.getPositionsIdsByRoleId(roleId);
			if (posIds != null && posIds.length > 0) {
				hql.append(" and ");
				hql.append(HqlUtils.buildAndCondition("ps", "posId", posIds));
			}

			List values = new ArrayList();
			if (form != null) {
				if (StringUtils.isNotBlank(form.getPosCode())) {
					hql.append(" and ps.posCode like ?");
					values.add("%" + form.getPosCode() + "%");

				}
				if (StringUtils.isNotBlank(form.getPosName())) {
					hql.append(" and ps.posName like ?");
					values.add("%" + form.getPosName() + "%");
				}
			}
			
			//排序
			hql.append(HqlUtils.buildOrderBy(page, "ps"));

			acPartyRoleDao.findPage(pg, hql.toString(), values);
			List<OmPositionForm> list = OmPositionConverter.convertToFormList(pg.getResult(), 
					sysCodeService.getItems(OrgConstant.SYS_CODE_ORG_STATUS));
			PageUtils.copy(pg, list, page);
			return page;
		}
		
		return null;
	}

	/**
	 * 查询与指定角色关联的岗位
	 * @param roleId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<OmPositionForm> getPositionsByRole(Long roleId) {
		return acPartyRoleDao.getPositionsByRoleId(roleId);
	}

	/**
	 * 查询不与指定角色关联的岗位
	 * @param roleId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<OmPositionForm> getPositionsNotAssociateRole(Long roleId) {
		return acPartyRoleDao.getPositionsNotAssociateRole(roleId);
	}

	/**
	 * 分配指定的角色给指定的用户
	 * @param roleId 角色id
	 * @param userIds 用户id数组
	 */
	public void assignRoleToUser(Long roleId, Long... userIds) {
		if (roleId != null && userIds != null && userIds.length > 0) {
			for (Long userId : userIds)
				acUserRoleDao.assignRoleToUser(roleId, userId);
		}
	}

	/**
	 * 分配指定的角色给指定的机构
	 * @param roleId 角色id
	 * @param orgIds 机构id数组
	 */
	public void assignRoleToOrg(Long roleId, Long... orgIds) {
		if (roleId != null && orgIds != null && orgIds.length > 0) {
			for (Long orgId : orgIds) {
				acPartyRoleDao.assignRoleToOrg(roleId, orgId);
			}
		}
	}
	
	/**
	 * 分配指定的角色给指定的工作组
	 * @param roleId 角色id 
	 * @param groupIds 机构id数组
	 */
	public void assignRoleToGroup(Long roleId, Long... groupIds){
		if (roleId != null && groupIds != null && groupIds.length > 0) {
			for (Long groupId : groupIds) {
				acPartyRoleDao.assignRoleToGroup(roleId, groupId);
			}
		}
	}

	/**
	 * 分配指定的角色给指定的职位
	 * @param roleId 角色id
	 * @param posIds 岗位id数组
	 */
	public void assignRoleToPosition(Long roleId, Long... posIds) {
		if (roleId != null && posIds != null && posIds.length > 0) {
			for (Long posId : posIds) {
				acPartyRoleDao.assignRoleToPosition(roleId, posId);
			}
		}
	}

	/**
	 * 使指定用户不具有某项角色
	 * @param roleId 角色id
	 * @param userId 用户id
	 */
	public void disAssociateRoleFromUser(Long roleId, Long userId) {
		acUserRoleDao.disAssociateRoleFromUser(roleId, userId);
	}

	/**
	 * 使指定用户列表不具备某项角色
	 * @param roleId 角色id
	 * @param userIds 用户id数组
	 */
	public void disAssociateRoleFromUser(Long roleId, Long[] userIds) {
		acUserRoleDao.disAssociateRoleFromUsers(roleId, userIds);
	}

	/**
	 * 使指定的机构不具有指定角色
	 * @param roleId
	 * @param orgIds
	 */
	public void disAssociateRoleFromOrg(Long roleId, Long... orgIds) {
		// 删除机构与角色的关联,操作AC_PARTY_ROLE
		if (roleId != null && orgIds != null && orgIds.length > 0) {
			for (Long orgId : orgIds) {
				acPartyRoleDao.disAssociateRoleFromOrg(roleId, orgId);
			}
		}
	}
	
	/**
	 * 使指定的工作组不具有指定角色
	 * @param roleId
	 * @param groupIds
	 */
	public void disAssociateRoleFromGroup(Long roleId, Long... groupIds) {
		// 删除机构与角色的关联,操作AC_PARTY_ROLE
		if (roleId != null && groupIds != null && groupIds.length > 0) {
			for (Long groupId : groupIds) {
				acPartyRoleDao.disAssociateRoleFromGroup(roleId, groupId);
			}
		}
	}

	/**
	 * 使指定岗位不具有指定角色
	 * @param roleId
	 * @param posIds
	 */
	public void disAssociateRoleFromPos(Long roleId, Long... posIds) {
		if (roleId != null && posIds != null && posIds.length > 0) {
			for (Long posId : posIds)
				acPartyRoleDao.disAssociateRoleFromPos(roleId, posId);
		}
	}

	/**
	 * 根据用户id分页获取用户本身的角色列表
	 * @author 舒军
	 * @param userId 用户id
	 * @param page 分页对象
	 * @return 用户本身的角色分页列表
	 */
	@Transactional(readOnly = true)
	public Page<AcRoleForm> getRolePageByUserId(Long userId, Page<AcRoleForm> page) {
		if (userId != null) {
			// 建立分页对象
			Page<AcRole> pg = PageUtils.newPageInstance(page);

			String hql = "select ps from AcRole ps,AcUserRole us where us.roleId = ps.roleId and us.userId=?";
			acRoleDao.findPage(pg, hql, userId);

			// 转换为Form对象列表并赋值到原分页对象中
			List<AcRoleForm> list = AcRoleConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
		}
		return page;
	}

	/**
	 * 获取与指定机构不关联AcRoleForm列表
	 * @author 舒军
	 * @param orgIdId 机构id
	 * @return AcRoleForm列表
	 */
	@Transactional(readOnly = true)
	public Page<AcRoleForm> getRolesUnAssociateOrg(Long orgId,Page<AcRoleForm> page) {
		if (orgId != null) {
			// 建立新的分页对象
			Page<AcRole> pg = PageUtils.newPageInstance(page);
			
			// 获取授权的角色id
			Long[] authRoleIds = CollectionUtils.toLongArray(this.getRoleIdsByOrgId(orgId));
			String hql = "from AcRole ps where 1=1 ";
			if( authRoleIds != null && authRoleIds.length > 0){
				hql += " and " + HqlUtils.buildAndCondition("ps", "roleId", authRoleIds);
			}
			
			pg = this.acRoleDao.findPage(pg,hql);
			
			// 转换为Form对象列表并赋值到原分页对象中
			List<AcRoleForm> list = AcRoleConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
		}
		return page;
	}
	
	/**
	 * 获取与指定工作组不关联AcRoleForm列表
	 * @param groupId 工作组id
	 * @return AcRoleForm列表
	 */
	@Transactional(readOnly = true)
	public Page<AcRoleForm> getRolesUnAssociateGroup(Long groupId,Page<AcRoleForm> page) {
		if (groupId != null) {
			// 建立新的分页对象
			Page<AcRole> pg = PageUtils.newPageInstance(page);
			
			// 获取授权的角色id
			Long[] authRoleIds = CollectionUtils.toLongArray(this.getRoleIdsByGroupId(groupId));
			String hql = "from AcRole ps where 1=1 ";
			if( authRoleIds != null && authRoleIds.length > 0){
				hql += " and " + HqlUtils.buildAndCondition("ps", "roleId", authRoleIds);
			}
			
			pg = this.acRoleDao.findPage(pg,hql);
			
			// 转换为Form对象列表并赋值到原分页对象中
			List<AcRoleForm> list = AcRoleConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
		}
		return page;
	}

	/**
	 * 获取与指定岗位不关联AcRoleForm列表
	 * @author 舒军
	 * @param orgIdId 岗位id
	 * @return AcRoleForm列表
	 */
	@Transactional(readOnly = true)
	public Page<AcRoleForm> getRolesUnAssociatePos(Long posId, Page<AcRoleForm> page) {
		if (posId != null) {
			// 建立新的分页对象
			Page<AcRole> pg = PageUtils.newPageInstance(page);
			
			// 获取授权的角色
			List<Long> authRoleIds = this.getRoleIdsByPosId(posId);
			String hql = "from AcRole ps where 1=1";
			StringBuffer sb = new StringBuffer();
			for (Long roleId : authRoleIds) {
				sb.append(" and ps.roleId !=" + roleId);
			}
			hql = hql + sb.toString();
			
			pg = this.acRoleDao.findPage(pg,hql);
			
			// 转换为Form对象列表并赋值到原分页对象中
			List<AcRoleForm> list = AcRoleConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
		}
		return page;
	}

	/**
	 * 根据工作组id删除关联角色
	 */
	public void disAssociationRoleFromGroup(Long groupId) {
		acRoleDao.disAssociationRoleFromGroup(groupId);
	}
	
	/**
	 * 根据机构ID删除关联角色
	 */
	public void disAssociationRoleByOrgId(Long orgId) {
		acRoleDao.disAssociationRoleByOrgId(orgId);
	}
	
	/**
	 * 查询与指定角色关联的所有用户
	 * @param roleId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<OmUserForm> getUsersByDirectRole(Long roleId) {
		if (roleId != null) {
			String hql = "select os from AcUserRole ps, OmUser os where ps.userId=os.userId and ps.roleId=?";
			List values = new ArrayList();
			values.add(roleId);
			
			List<OmUser> list = acUserRoleDao.find(hql, values);
			return OmUserConverter.convertToFormList(list);
		}
		return null;
	}
	
	//判断角色表中是否有匹配的记录
	public boolean hasRoleLikeKeyword(List<AcRoleForm> list,String keyword){
		if(keyword != null && keyword.trim().length()>0 && list != null && list.size()>0){
			for(AcRoleForm form :list){
				if(isRoleLikeKeyword(form.getRoleId(),keyword))
					return true;
			}
		}
		
		return false;
	}
	
	public boolean isRoleLikeKeyword(Long roleId,String keyword){
		if(roleId != null && keyword != null && keyword.trim().length()>0){
			AcRoleForm form = this.get(roleId);
			if(isRoleLikeKeyword(form,keyword))
				return true;
			else{
				List<OmUserForm> userList = this.getUsersByDirectRole(roleId);
				if(userList != null && userList.size()>0){
					for(OmUserForm userForm:userList){
						if(this.omUserService.isUserLikeKeyword(userForm.getUserId(), keyword))
							return true;
					}
				}
			}
		}
		return false;
	}
	
	public boolean isRoleLikeKeyword(AcRoleForm form,String keyword){
		if(form != null && keyword != null && keyword.trim().length()>0){
			if( form.getRoleName().length()>=keyword.length()){
				String subStr = form.getRoleName().substring(0,keyword.length());
				if(subStr.equals(keyword))
					return true;
			}
		}
		return false;
	}

	@Override
	public List<OmUserForm> getUsersByDirectRoles(Long roleId, Long orgId) {
		if (roleId != null) {
			String hql = "select os from AcUserRole ps, OmUser os,OmUserOrg uorg " +
					" where ps.userId=os.userId and  uorg.userId=os.userId and uorg.orgId="+orgId+
					" and ps.roleId=?";
			List<OmUser> list = acUserRoleDao.find(hql, roleId);
			return OmUserConverter.convertToFormList(list);
		}
		return null;
	}
}
